﻿using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Reflection;
using System.Text;
using System.Web.UI;
using VitCode.BaseDataPageCreator;
using VitCode.Castle.DataAccess;
using VitCode.Castle.Entities;
using VitCode.Castle.Helper;
using VitCode.Castle.Management;
using VitCode.Web.UI;
using VitCode.Web.UI.WebControls;

namespace VitCode.Web.BackStageManagement
{
    public partial class UserList : VcPage
    {
        private BaseDataManager m_Acc = new BaseDataManager();
        private PageBuilder m_PageBuilder;
        private  string sql = " SELECT a.Id,a.Code,a.Name,a.Mobile,a.Email,a.Number,b.Name UserGroup  FROM  VitCode_Castle_User a  left outer join VitCode_Castle_UserGroup b on a.UserGroupId =b.Id ";


        private string SettingXmlPath
        {
            get { return AppDomain.CurrentDomain.BaseDirectory + "Setting\\BaseDataSet.xml"; }
        }


   

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write("<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>");
            ListGridInfo.DataSourceDelegate = new PaginationGrid.GridDataSourceDelegate(BindList);
            if (String.IsNullOrEmpty(GenericContext.CurrUserCode))
            {
                Response.Redirect("../Default.aspx");
            }
            if (!IsPostBack)
            {
                ListGridInfo.BindGrid();
            }
          
             
       }


        private object BindList()
        {
            DataTable dt = m_Acc.GetDataTableBySql(sql);
            dt.Columns.Add("Role", typeof(string));
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string strRole = "";
                    string strUserId = dt.Rows[i]["id"].ToString();
                    string sqlStr =
                        "select a.Name from  VitCode_Castle_Role  a join VitCode_Castle_User_Role b on a.Id = b.RoleId join VitCode_Castle_User c on c.id = b.UserId  where c.Id='" + strUserId + "'";

                    DataTable dt2 = new DataTable();
                    dt2 = m_Acc.GetDataTableBySql(sqlStr);
                    if (dt2.Rows.Count > 0)
                    {
                        for (int j = 0; j < dt2.Rows.Count; j++)
                        {
                            strRole += dt2.Rows[j][0].ToString() + ",";
                        }
                        strRole = strRole.Substring(0, strRole.Length - 1);
                        dt.Rows[i]["Role"] = strRole;
                    }
                }
            }
            if (dt.Rows.Count > 0)
            {
                btnRealDelete.Enabled = true;
                btn_UserRoleAll.Enabled = true;
            }
            return dt;

        }

        protected void btnRealDelete_Click(object sender, EventArgs e)
        {
         string strDelVal = ListGridInfo.GetSelectedItem(1);
            string[] strDel = strDelVal.Split(',');
            for (int i = 0; i < strDel.Length; i++)
            {
                if (strDel[i].Length == 36)
                {
                    var castle = new CastleAccess();
                    if (castle.CheckIsAdmin(strDel[i]))
                    {
                        IList objList = m_Acc.GetObjectList(new User().GetType().Name, "Id", strDel[i]);
                        if(objList != null && objList.Count > 0)
                        {
                            var currentUser = (User) objList[0];
                            var strName = currentUser.Name;
                        
                        Alert.MessageBox( strName + "為系統管理員，不能刪除!");
                        return;
                        }
                    }
                   
                }
            }
            if (string.IsNullOrEmpty(strDelVal.Trim()))
            {
                Alert.MessageBox("請選擇要刪除的用戶!");
                return;
            }
            var cch = new CreateControlHelper();
            if (m_PageBuilder == null)
                m_PageBuilder = new PageBuilder(this, SettingXmlPath);
            Type classType = m_PageBuilder.m_LoadHelper.GetClassTypeByClassNodeName("User");
            string proName = m_PageBuilder.GetPageKeyField("User");
            PropertyInfo pi = classType.GetProperty(proName);
            var acc = new BaseDataAccess();
            acc.BeginTransaction();
            try
            {
                StringCollection sc = acc.DeleteReErrMsg(false, strDelVal, pi.PropertyType, classType);

                if (sc.Count == 0)
                {
                    acc.Commit();
                    Alert.MessageBox("徹底刪除成功");
                }
                else
                {
                    var sb = new StringBuilder();
                    sb.Append("部分資料不能刪除,原因如下:\r\n");
                    for (int i = 0; i < sc.Count; i++)
                    {
                        sc[i] = sc[i].Replace('#', ' ');
                        string str = sc[i];
                        sb.Append(str + "\r\n");
                    }
                    acc.RollBack();
                    Alert.MessageBox(sb.ToString());
                }
                ListGridInfo.BindGrid();
            }
            catch(Exception ex)
            {
                acc.RollBack();
                throw;
            }
            finally
            {
                acc.CloseSession();
            }
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            string strLink = "UserInsert.aspx";
            Response.Redirect(strLink, false);
        }

        public string IsCheckString
        {
            get
            {
                string reVal = "";
                var obj = Session["IsCheckString"];
                if (obj != null && obj is string)
                    reVal = obj.ToString();
                return reVal;
            }
            set
            {
                Session["IsCheckString"] = value;
            }
        }

        /// <summary>
        /// 批量設置用戶的角色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button_UserGroupRole_Click(object sender, EventArgs e)
        {
            string sCheck = ListGridInfo.GetSelectedItem(1);
            if (string.IsNullOrEmpty(sCheck))
            {
                Alert.MessageBox("未選擇用戶！");
                return;

            }

            IsCheckString= sCheck; //頁面間調用
            Response.Redirect("RolesUpdateAll.aspx", false);
        }

        protected void ListGridInfo_OnGridItemSelect(object sender, PaginationGridItemSelectArgs e)
        {
              string key = e.LastClickColumnIndex;
              string val = e.SelectedDataKeyValue;
              if (key == "2")
              {
                  Response.Redirect("UserUpdate.aspx?&Id=" + val,false);
              }
              else
              {
                   var win = new Window(Page, "密碼修改")
                          {
                              Height = 280,
                              Width = 520,
                              Scrollbars = true,
                              Status = true,
                              Name = "密碼修改"
                          };
                   win.ShowModalDialog("PassUpdate.aspx?&Id=" + val, new string[] { "hdCheckInfo" });
              }
            
           
        }

        protected void btnQuery_Click1(object sender, EventArgs e)
        {
            sql = " SELECT a.Id,a.Code,a.Name,a.Mobile,a.Email,a.Number,b.Name UserGroup  FROM  VitCode_Castle_User a  left outer join VitCode_Castle_UserGroup b on a.UserGroupId =b.Id ";
            if (ddlCondition.SelectedItem.Text != "" && txtValue.Text.Trim().Length > 0)
            {

                if (rbtAmount.Checked)
                    sql += "  where " + ddlCondition.SelectedItem.Value + " = '" + txtValue.Text.Trim() + "'";
                else sql += "  where " + ddlCondition.SelectedItem.Value + " like '%" + txtValue.Text.Trim() + "%'";


            }
            
            ListGridInfo.DataSourceDelegate = new PaginationGrid.GridDataSourceDelegate(BindList);
            ListGridInfo.BindGrid();
        }

        protected void ListGridInfo_OnBeforeExportData(object sender, PaginationGridBeforeExportDataArgs e)
        {
            if(e.ExportMode == PaginationGridDataExportMode.All)
                return;
        }
    }
}
